<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Brands;
use App\Models\CustomerExperienceAssessment;
use Illuminate\Support\Facades\DB;
use App\Models\brandUserRelation;

class BrandsController extends Controller
{
    /*
     * get brand by user input
     */
    function getBrandsByInput(Request $request){
        $string = $request->input('data');
        if(!$string){
            return $this->getBrandsAll();
        }
        //select from DB
        $result = Brands::where('name', 'like', "%$string%")->get(['name'])->toArray();
        if(empty($result)){
            $return = array();
            return json_encode(array('code' => '0', 'msg' => 'No brand searched', 'result' => $return));
        }
        $return = array();
        foreach ($result as $v){
            $return[] =  $v['name'];
        }
        return json_encode(array('code' => '0', 'msg' => 'success', 'result' => $return));
    }

    /*
     * get all brands
     */
    function getBrandsAll(){
        $result = Brands::distinct()->get(['name'])->toArray();
        if(empty($result)){
            return null;
        }
        $return = array();
        foreach ($result as $v){
            $return[] =  $v['name'];
        }
        return json_encode(array('code' => '0', 'msg' => 'success', 'result' => $return));
    }

    /*
     * create new brand
     */
    function create(Request $request){
        $brandName = $request->input('brandName') ? $request->input('brandName') : null;
        $openId = $request->input('openId') ? $request->input('openId') : null;

        if(!$brandName || !$openId){
            return false;
        }
        $items = config('app.items');
        //save new brand
        $brand = new Brands();
        $brand->name = $brandName;
        $brand->uid = $openId;
        $result = $brand->save();
        if($result){
            return json_encode(array('code' => '0', 'msg' => 'The new brand is saved', 'id' => $brand->id, 'items' => $items));
        }else {
            return json_encode(array('code' => '1', 'msg' => 'The new brand fail to save'));
        }
    }

    /*
     * get brand by name
     */
    function getBrandByName(Request $request){
        $brandName = $request->input('brandName') ? $request->input('brandName') : null;
        $openId = $request->input('openId') ? $request->input('openId') : null;
        if(!$brandName || !$openId){
            return json_encode(array('code' => '1', 'msg' => 'empty request field'));
        }

        //select from db
        $finished = false;
        $items = config('app.items');
        $result = Brands::where('name', $brandName)->where('editable', '1')->get(['id'])->first();
        if(empty($result)){
            $result = Brands::where('name', $brandName)->where('editable', '0')->get(['id'])->first();
            $finished = true;
        }
        if(empty($result)){
            return json_encode(array('code' => '1', 'msg' => 'No brand in DB'));
        }
        //get the first item information
        $assessmentFirst = CustomerExperienceAssessment::where('user', $openId)
                                                        ->where('brand_id', $result->id)
                                                        ->where('item', $items[0])
                                                        ->get(['image', 'description', 'skip'])
                                                        ->first();
        if($assessmentFirst){
            $assessmentFirstArray = $assessmentFirst->toArray();
            $imagePath = "images/user/" . $openId . '/' . $assessmentFirstArray['image'];
            if(file_exists($imagePath)){
                $assessmentFirstArray['uploadImagePath'] = url('/') . '/' . $imagePath;
            }else{
                $assessmentFirstArray['uploadImagePath'] = '';
            }
            $assessmentFirstArray['skip'] = $assessmentFirstArray['skip'] ? true : false;
            $assessmantFirstResult = array('hasFirst' => true, 'detail' => $assessmentFirstArray);
        }else{
            $assessmantFirstResult = array('hasFirst' => false, 'detail' => array());
        }
        return json_encode(array('code' => '0', 'msg' => 'Success', 'finished' => $finished, 'id' => $result->id, 'items' => $items, 'assessmentFirst' => $assessmantFirstResult));
    }
    /*
     * make the brand can not be changed
     */
    function makeBrandNotEditable(Request $request){
        $brandId = $request->input('brandId') ? $request->input('brandId') : '';
        if(!$brandId){
            return json_encode(array('code' => '1', 'msg' => 'request data empty'));
        }
        $brand = Brands::where('id', $brandId)
                    ->first();
        if(!$brand){
            return json_encode(array('code' => '2', 'msg' => 'no such a brand'));
        }
        $brand->editable = '0';
        $result = $brand->save();
        if(!$result){
            return json_encode(array('code' => '3', 'msg' => 'brand save failed'));
        }
        return json_encode(array('code' => '0', 'msg' => 'brand save success'));
    }
    /*
     * get current brand info, to check if it is editable
     */
    function getCurrentBrandInfo(Request $request){
        $brandId = $request->input('brandId') ? $request->input('brandId') : '';
        if(!$brandId){
            return json_encode(array('code' => '1', 'msg' => 'request data empty'));
        }
        $brand = Brands::where('id', $brandId)
            ->first();
        if(!$brand){
            return json_encode(array('code' => '2', 'msg' => 'no such a brand'));
        }
        return json_encode(array('code' => '0', 'msg' => 'success', 'result' => $brand));
    }
    /*
     * get brands info by user
     */
    function getAssessmentInfoByUser(Request $request){
        $openId = $request->input('openId') ? $request->input('openId') : '';
        if(!$openId){
            return json_encode(array('code' => '1', 'msg' => 'request data empty'));
        }
        $brands = Brands::where('uid', $openId)->get();
        $unfinished = array('flag' => false, 'brandName' => '');
        $brandsInfo = array();
        if($brands){
            $brands = $brands->toArray();
            //group by brand name
            $brandsGroupBy = Brands::where('uid', $openId)->where('editable', '0')->groupBy('name')->get(['name'])->toArray();
            foreach ($brandsGroupBy as $v) {
                foreach ($brands as $value) {
                    if ($v['name'] == $value['name']) {
                        $value['showArrow'] = false;
                        $brandsInfo[$v['name']][] = $value;
                    }
                    if ($value['editable'] == '1') {
                        $unfinished['flag'] = true;
                        $unfinished['brandName'] = $value['name'];
                    }
                }
            }

            foreach ($brandsInfo as $key => $value){
                foreach ($value as $k => $v){
                    $result = DB::table('friction_evaluation')
                        ->leftjoin('customer_experience_assessment', 'customer_experience_assessment.id', 'friction_evaluation.cea_id')
                        ->leftjoin('brands', 'brands.id', 'customer_experience_assessment.brand_id')
                        ->where('brands.id', $v['id'])
                        ->groupBy('friction_evaluation.user')
                        ->get(['friction_evaluation.user'])
                        ->count();
                    $brandsInfo[$key][$k]['commentsTotal'] = $result;
                }

            }
        }
        return json_encode(array('code' => '0', 'msg' => 'request success', 'result' => array('unfinished' => $unfinished,'brandsInfo' => $brandsInfo)));
    }

    function shareFrictionEvaluationFinalSave(Request $request){
        $brandId = $request->input('brandId') ? $request->input('brandId') : '';
        $openId = $request->input('openId') ? $request->input('openId') : '';
        if(!$brandId || !$openId){
            return json_encode(array('code' => '1', 'msg' => 'request data empty'));
        }
        $brandUserRelation = new brandUserRelation();
        $brandUserRelation->brand_id = $brandId;
        $brandUserRelation->user = $openId;
        $brandUserRelation->editable = '0';
        $result = $brandUserRelation->save();
        if(!$result){
            return json_encode(array('code' => '2', 'msg' => 'brand save failed'));
        }
        return json_encode(array('code' => '0', 'msg' => 'brand save success'));
    }
}
